<?php
class Admin_EventController extends Apps_Controller_Action_Admin {

	//LIST
	public function indexAction() {
		$this->actResolve('act_delete',
						  'delete', null, null, array('id' => $this->_getParam('item_checker')),
					 	  true);

		$tbEvent = new M_DbTable_Event();
		$grid 	= new Apps_Plugin_Grid('EventGrid');

		$grid->setData($tbEvent->getList())
			 ->setTableCaption('List MICE')
			 ->setTableColumnFormat(array(
			 		array('title'		=> 'ID',
			 			  'dataField'	=> 'id',
			 			  'class'		=> 'center'),
			 		array('title'		=> 'MICE',
			 			  'dataField'	=> 'title'),
			 		array('title'		=> 'Description',
			 			  'dataField'	=> 'description'),
			 		array('title'		=> 'Type',
	                      'html'        => function($rs) {
	                                            $labelEventType = new Apps_View_Helper_LabelEventType();
	                                            return $labelEventType->labelEventType($rs['type']);
	                                        },
			 			  'class'		=> 'center'),
			 		array('title'		=> 'View',
			 			  'html'        => array('<a href="/mice/detail?id=%d&t=%d" target="_blank"><i class="icon-list-alt"></i></a>',
			 			  				   array('id', 'type')),
			 			  'class'		=> 'center',
			 			  'width'       => '2%'),
			 		array('title'       => 'Edit',
			 			  'html'        => array('<a href="/admin/event/edit?id=%s"><i class="icon-edit" title="Sửa"></i></a>',
			 			  				   array('id')),
			 			  'width'       => '2%',
	 			  		  'class'		=> 'center'),
			 	    array('title'       => 'Delete',
			 			  'html'        => array('<a href="/admin/event/delete?id=%s" class="must-confirm" data-must-confirm-msg="Bạn có chắc là muốn xóa?"><i class="icon-remove" title="Xóa"></i></a>',
			 			  				   array('id')),
			 			  'width'       => '2%',
	 			  		  'class'		=> 'center')
			 		));
		$this->view->grid = $grid;
	}

	//ADD
	public function addAction() {
		$rq 		= $this->_request;
		$f 			= new Admin_Form_AddEvent();
		$tbEvent	= new M_DbTable_Event();
		$tbArticle 	= new M_DbTable_Article();

		if ($rq->isPost()) {
			if ($f->isValid($rq->getParams())) {
				// Upload thumbnail
				$uploader = new Apps_Plugin_Upload_File();
				$uploader->setMaxQuantity(1)
						 ->setSubCategory(Apps_Plugin_Upload_File::CAT_EVENT);
				$thumbnail = ($uploaded = $uploader->upload())
						 	 ? $uploaded['thumbnail']['uri']
						 	 : null;

				//resize images
				try {
				    $image = new Apps_Plugin_ResizeImages();
				    $image->load(PUBLIC_PATH .$thumbnail);
				    $image->resizeToWidth(200);
				    $image->save(PUBLIC_PATH .$thumbnail);
				} catch (Exception $e) {
				    //Excetion here
				}

				$data = $f->getValues();
				$data['thumbnail'] = $thumbnail;

				$keyFilterEvent = array('country_id',
									    'type',
									    'is_comming',
									    'description',
									   	 'meta_keyword',
									   	 'meta_description',
									     'header_title');

				$eventId = $tbEvent->safelyInsert($data, $keyFilterEvent);
				if ($eventId) {
					$this->_flashMessenger->addMessage(
						$tbArticle->addArticle($data, $eventId, $tbArticle::REFERENCE_TYPE_EVENT)
						? self::$msgAddSuccess
						: self::$msgAddFailed
					);
				}
				$this->_helper->redirector('index', null, null);
			}
		}
		$this->view->form = $f;
	}

	//EDIT Event
	public function editAction() {
		$rq = $this->_request;
		$id = $rq->getParam('id');

		$tbEvent = new M_DbTable_Event();
		$event 	= $tbEvent->getEvent($id);

		if (!$id || !$event) {
			$this->_helper->redirector('index');
		}

		$f = new Admin_Form_AddEvent();
		if ($rq->isPost()) {
			if ($f->isValid($rq->getParams())) {
				$tbArticle 	= new M_DbTable_Article();

				// Upload thumbnail - replace thumbnail if changed
				$rs = $tbArticle->getArticleByReference($id, $tbArticle::REFERENCE_TYPE_EVENT)->query()->fetch();
				$thumbnail = $rs['thumbnail'];

				if(Apps_Plugin_Upload_File::isUploaded('thumbnail')) {
					$uploader = new Apps_Plugin_Upload_File();
					$uploader->setMaxQuantity(1)
							 ->setSubCategory(Apps_Plugin_Upload_File::CAT_EVENT);

					$uploaded = $uploader->upload();
					if($uploaded) {
						unlink(Apps_Plugin_Upload_File::getPath($thumbnail)); // Delete ex-thumbnail
						$thumbnail = $uploaded['thumbnail']['uri'];
						//resize images
						try {
						    $image = new Apps_Plugin_ResizeImages();
						    $image->load(PUBLIC_PATH .$thumbnail);
						    $image->resizeToWidth(200);
						    $image->save(PUBLIC_PATH .$thumbnail);
						} catch (Exception $e) {
						    //Excetion here
						}
					}
				}

				$data = $f->getValues();
				$data['thumbnail'] = $thumbnail;

				$keyFilterEvent = array('country_id',
									    'type',
									    'is_comming',
									    'description',
									   	 'meta_keyword',
									   	 'meta_description',
									     'header_title');

				$rT = $tbEvent->safelyUpdate($data, array('id =?' => $id) , $keyFilterEvent);
				$rA = $tbArticle->updateArticle($data, $id, $tbArticle::REFERENCE_TYPE_EVENT);

				if (!$rT && !$rA) {
					$this->_flashMessenger->addMessage(self::$msgUpdateFailed);
				} else {
					$this->_flashMessenger->addMessage(self::$msgUpdateSuccess);
				}
				$this->_helper->redirector('index');
			}
		}
		$f->setLegend('Edit MICE');
		$f->populate($event->query()->fetch());
		$this->view->form = $f;
		$this->render('add');
	}

	//DELETE
	public function deleteAction() {
		$rq = $this->_request;
		$id = $rq->getParam('id');

		if (!$id) {
			$this->_helper->redirector('index');
		}

		$tbEvent = new M_DbTable_Event();
		$tbArticle = new M_DbTable_Article();

		if (is_numeric($id)) {
			if ($tbEvent->safelyDelete('id ='. $id)) {
				$this->_flashMessenger->addMessage(
					$tbArticle->deleteArticle($id, $tbArticle::REFERENCE_TYPE_EVENT)
					? self::$msgDeleteSuccess
					: self::$msgDeleteError
				);
			}
		} elseif (is_array($id)) {
			foreach ($id as $v) {
				if ($tbEvent->safelyDelete('id ='. $v)) {
					$tbArticle->deleteArticle($v, $tbArticle::REFERENCE_TYPE_EVENT);
				}
			}
		}

		$this->_helper->redirector('index');
	}

}